import axios from 'axios'
import Vue from 'vue';
import store from '../store/index'

import Utils from "../common/Utils";
import settle from "axios/lib/core/settle"
import buildURL from "axios/lib/helpers/buildURL"
import qs from "qs";



axios.defaults.baseURL = Utils.ApiUrl;

// #ifdef H5
// axios.defaults.transformResponse = [
// 	function(data) {
// 		return Utils.getRealJsonData(data)
// 		// return data
// 	}
// ];
// #endif
//拦截器
const whiteRoute = [`/signup`, `/protocols/user_protocol/latest`,
	`/products`, `/carousel/items`,
	`/dictionaries/product_category`, `/dictionaries/product_category`
];

function hasInWhite(url) {
	var hasUrl = false;
	for (let w of whiteRoute) {
		if (url.indexOf(w) != -1) {
			//console.log("url=", url)
			hasUrl = true;
		}
	}
	return hasUrl
}
axios.interceptors.request.use(config => {

	let userToken = store.state.userToken;
	let expiration = store.state.expiration;
	//console.log('config=', config)
	let hasUrl = hasInWhite(config.url)
	//console.log("hasUrl=", hasUrl)
	if (config.method === 'get') {
		config.paramsSerializer = function(params) {
			return qs.stringify(params, {
				arrayFormat: 'repeat'
			})
		}

	} else if (config.method == 'post') {

		config.headers['content-type'] = "application/json"
		//config.data=qs.stringify(config.data);
	}
	if (userToken && !hasUrl) {
		//console.log("expiration=", Utils.formatDate(new Date(expiration), 'yyyy-MM-dd HH:mm:ss'))
		let expDate = new Date(expiration);
		let curDate = new Date();
		//console.log(expiration, expDate.getTime())
		let minutesDifference = Math.floor((expDate.getTime() - curDate.getTime()) / 1000 / 60)
		//console.log("minutesDifference =", minutesDifference)
		if (minutesDifference <= 60) {
			store.commit("LOGOUT")
			uni.navigateTo({
				url: '/pages-publics/login/login'
			})
			return Promise.reject(new Error('请重新登录'));;
		}
		config.headers["Authorization"] = `Bearer ${userToken}`;		 

	}
	//config.headers['content-type'] = "application/json,text/plain"
	return config;
}, error => {
	return Promise.reject(error);
});
//拦截返回结果
axios.interceptors.response.use(async response => {
	uni.hideLoading();

	if (response.status) {
		if (response.status == 200) {
			let res = response.data;
			if (res.Result == 401) {
				//store.commit("LOGOUT")
				uni.navigateTo({
					url: '/pages-publics/login/login'
				})
			} else if (res.Result == 404) {
				uni.showToast({
					icon: 'none',
					title: "没有访问到API接口"
				})
			}
			if (res.Result == 403) {
				uni.showToast({
					icon: 'none',
					title: "权限错误，请联系管理员"
				})
			}

		} else if (response.status == 401) {
			store.commit("LOGOUT")
			uni.navigateTo({
				url: '/pages-publics/login/login'
			})
			//location.reload();
			return Promise.reject(err);
		} else if (response.status == 403) {
			uni.showToast({
				icon: 'none',
				title: "权限错误，请联系管理员"
			})
			//location.reload();
		} else if (response.status == 404) {
			uni.showToast({
				icon: 'none',
				title: "没有访问到API接口"
			})
		} else if (response.status == 404) {
			uni.showToast({
				icon: 'none',
				title: "没有访问到API接口"
			})
		} else {
			// uni.showToast({
			// 	title: '服务器异常',
			// 	icon: 'none'

			// });
			return Promise.reject(err);
		}


	} else {

		uni.showToast({
			title: `服务器异常${response.errMsg}`,
			icon: 'none'

		})
	}


	return response;
}, err => {
	uni.hideLoading();
	if (err.response) {



		if (err.response.status === 401) {
			//store.commit("LOGOUT")
			uni.navigateTo({
				url: '/pages-publics/login/login'
			})

			//location.reload();
			return Promise.reject(err);
		} else if (err.response.status == 403) {

			uni.showToast({
				icon: 'none',
				title: "权限错误，请联系管理员"
			})
			uni.navigateTo({
				url: '/pages-publics/login/login'
			})
			//location.reload();
		} else if (err.response.status == 404) {
			uni.showToast({
				icon: 'none',
				title: "没有访问到API接口"
			})
		} else if (err.response.status == 400) {
			if (err.response.data.message) {
				uni.showToast({
					icon: 'none',
					title: err.response.data.message
				})
			} else {
				uni.showToast({
					icon: 'none',
					title: "服务器错误"
				})
			}
			return Promise.reject(err);
		} else {
			if (err.response.data.message) {
				uni.showToast({
					icon: 'none',
					title: err.response.data.message
				})
			} else {
				uni.showToast({
					icon: 'none',
					title: "服务器错误"
				})
			}
			return Promise.reject(err);
		}


	} else {
		console.log(err.message)
		if (err.message) {
			uni.showToast({
				icon: 'none',
				title: err.message
			})
		} else {
			uni.showToast({
				icon: 'none',
				title: "服务器错误"
			})
		}

		return Promise.reject(err);
	}


});
// #ifndef H5


axios.defaults.adapter = function(config) {
	return new Promise((resolve, reject) => {
		var data = config.data;
		if (typeof config.data === 'number') {
			data = config.data + '';
		}
		uni.request({
			method: config.method.toUpperCase(),
			url: buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: data,

			dataType: 'jsonp',
			// responseType: config.responseType,
			// sslVerify: config.sslVerify,
			complete: function complete(response) {
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};

				settle(resolve, reject, response);
			}
		})
	})
}
// #endif